#pragma once
#include <iostream>
#include <string>
#include <pthread.h>


enum class Status
{
    NEW = 0, // 新建
    RUNNING, // 运行中
    EXIT     // 退出
};

typedef void* (*func_t)(void *);

class Thread
{
public:
    Thread(int num = 0, func_t func = nullptr, void *args = nullptr)
        : _tid(0), _status(Status::NEW), _func(func), _args(args)
    {
        char name[128];
        snprintf(name, sizeof(name), "thread-%d", num);
        _name = name;
    }
    pthread_t getTID() const
    {
        return _tid;
    }

    std::string getName() const
    {
        return _name;
    }

    Status getStatus() const
    {
        return _status;
    }

    static void *runHelper(void *args)
    {
        Thread *myThis = static_cast<Thread *>(args);

        myThis->_func(myThis->_args);
        return nullptr;
    }
    void run()
    {
        int ret = pthread_create(&_tid, nullptr, runHelper, this);

            if (ret != 0)
        {
            std::cerr << "create thread fail" << std::endl;
            exit(1);
        }
        _status = Status::RUNNING;
    }
    void join()
    {
        int ret = pthread_join(_tid, nullptr);
        if (ret != 0)
        {
            std::cerr << "thread join fail" << std::endl;
            exit(1);
        }
        _status = Status::EXIT;
    }

private:
    pthread_t _tid;    // 线程ID
    std::string _name; // 线程名
    Status _status;    // 线程状态
    func_t _func;      // 线程回调函数
    void *_args;       // 传递给回调函数的参数
};
